package com.english.config;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.english.common.CommonResponse;
import com.english.domain.User;
import com.english.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import java.io.IOException;

@Component
public class JwtInterceptor extends InterceptorRegistry implements HandlerInterceptor {
    @Resource
    private UserService userService;
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object object) throws IOException {

        //获取token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为 401
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(new CommonResponse<>(401, "Unauthorized"))); // 将 CommonResponse 对象转为 JSON 并返回
            return false;
        }
        //获取token的userid
        String userId;
        try {
            //解密获取
            userId = JWT.decode(token).getAudience().get(0); //得到token中的userid载荷
        } catch (JWTDecodeException j) {
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为 401
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(new CommonResponse<>(401, "Unauthorized"))); // 将 CommonResponse 对象转为 JSON 并返回
            return false;
        }

        //根据userid查询数据库
        User user = userService.getById(userId);

        if(user == null){
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为 401
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(new CommonResponse<>(401, "Unauthorized"))); // 将 CommonResponse 对象转为 JSON 并返回
            return false;
        }
        // 用户密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为 401
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(new CommonResponse<>(401, "Unauthorized"))); // 将 CommonResponse 对象转为 JSON 并返回
            return false;
        }
        return true;
    }
}
